package com.example.demo.Config;

import com.example.demo.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    @ExceptionHandler
    public Object handler(Exception e){
        log.error("发生异常, e: ", e);
        return Result.fail();
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//声明状态码,不能写数字
    @ExceptionHandler
    public Object handler(ArrayIndexOutOfBoundsException e){
        log.error("发生异常, e: ", e);
        return Result.fail("发生数组越界异常");
    }

    @ExceptionHandler
    public Object handler(NullPointerException e){
        log.error("发生异常, e: ", e);
        return Result.fail("发生空指针异常");
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Object handler(NoResourceFoundException e){
        log.error("发生异常, e: {}, path: {}", e.getResourcePath(), e.getResourcePath());
        return Result.fail("发生NoResourceFoundException异常");
    }
}
